/*
  author：钱慧敏
  email:1147175965@qq.com
*/


/*根据data添加菜单项*/
function addContextMenuItems(data){
  var time=null;
  if(data.length>0) {
    time=new Date().getTime();
    //创建根菜单项
    chrome.contextMenus.create({
      title:'RMenus(网站功能菜单)',
      contexts:['all'],
      id:'RMenus_AddOn_MenusRoot',
      documentUrlPatterns:['http://*/*','https://*/*']
    });
  }
  //限定菜单添加时间为100ms，防止单个页面过大的菜单执行时间导致无法及时响应其他的页面右键
  //虽然时间只会增大，但是考虑到系统时间恰好在过程中重置的可能性，比如系统时间比实际的慢了一天，用户恰好重置了
  for(var i=0; time <= (new Date().getTime()) && (new Date().getTime())<time+100 && i<data.length;i++){
    if(data[i].parentId==null) data[i].parentId="RMenus_AddOn_MenusRoot";
    try{chrome.contextMenus.create(data[i]);}
    catch(err){console.log(err);}
  }
  time=null;
}

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse){
    switch(request.etype){
      case "contextmenu"://菜单消息处理
        chrome.contextMenus.removeAll();//删除此扩展所添加的全部菜单
        addContextMenuItems(request.info);
        chrome.cookies.set(//设置cookie用于和contentscript共享数据[2]
          {
            url:sender.tab.url,
            name:"is_conextmenu_loaded",
            value:"1"
          }, function(){});
        //sendResponse({time:time});//即使不主动调用，当函数退出时也会自动向发送信息的content_scripts返回空的rsponse
        break;
      default:
        //sendResponse({});
        break;
    }
  }
);

chrome.contextMenus.onClicked.addListener(
  function(info,tab){
    /*info,Information about the item clicked and the context where the click happened.
    https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/menus/OnClickData

      tab,The details of the tab where the click took place. If the click did not take place in a tab, this parameter will be missing.
    https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/tabs/Tab
    */
    chrome.tabs.sendMessage(tab.id,{etype:"contextmenu_onclick",data:{info:info,tab:tab}},function(){});
  }
);
